package com.virtualparadigm.hierarchy;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

//IN ORDER DEPTH FIRST TRAVERSAL
public class PreOrderDepthFirstIterator<T> implements Iterator<Hierarchical<T>>
{
	private Stack<Hierarchical<T>> visitStack;
	
	public PreOrderDepthFirstIterator(Hierarchical<T> hierarchical)
	{
		this.visitStack = new Stack<Hierarchical<T>>();
		this.visitStack.push(hierarchical);
	}

//	@Override
	public boolean hasNext()
	{
		if(this.visitStack.size() > 0)
		{
			return true;
		}
		return false;
	}

//	@Override
	public Hierarchical<T> next()
	{
		Hierarchical<T> hierarchical = this.visitStack.pop();
		if(hierarchical != null)
		{
			List<Hierarchical<T>> children = hierarchical.getChildren();
			if(children != null && children.size() > 0)
			{
				List<Hierarchical<T>> reverseChildren = this.reverse(children);
				if(reverseChildren != null)
				{
					for(int i=0; i<reverseChildren.size(); i++)
					{
						this.visitStack.push(reverseChildren.get(i));
					}
				}
			}
		}
		return hierarchical;
	}

//	@Override
	public void remove()
	{
		// TODO Auto-generated method stub
		
	}
	
	
	private List<Hierarchical<T>> reverse(List<Hierarchical<T>> hierarchicalList)
	{
		List<Hierarchical<T>> reverseList = null;
		if(hierarchicalList != null)
		{
			reverseList = new ArrayList<Hierarchical<T>>();
			for(int i=hierarchicalList.size()-1; i>=0; i--)
			{
				reverseList.add(hierarchicalList.get(i));
			}
		}
		return reverseList;
	}
	
}